package com.unswift.window.dialog;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import com.unswift.QuickApplication;
import com.unswift.constant.ButtonConstant;
import com.unswift.constant.QuickConstant;
import com.unswift.utils.DbSession;
import com.unswift.utils.DbSession.FindDataBack;
import com.unswift.utils.ObjectUtils;
import com.unswift.window.extend.Attribute;
import com.unswift.window.factory.ButtonFactory;
import com.unswift.window.factory.FormFactory;
import com.unswift.window.factory.MessageFactory;
import com.unswift.window.factory.PanelFactory;
import com.unswift.window.factory.ScrollFactory;
import com.unswift.window.factory.TableFactory;
import com.unswift.window.table.Table;

@SuppressWarnings("serial")
public class ConnectionDatabaseDialog extends QuickDialog{

	private int width;
	private JTextField jdbcDriver;
	private JTextArea jdbcUrl;
	private JTextField jdbcUsername;
	private JTextField jdbcPassword;
	private String action;
	
	public ConnectionDatabaseDialog(JFrame frame, String action) {
		super(frame, "链接数据库", false);
		this.action=action;
		setSize(frame);
		JPanel root = (JPanel)this.getContentPane();
		initForm(root);
		initBottom(root);
		setVisible(true);
	}
	
	private void setSize(JFrame frame) {
		int fwidth=frame.getWidth();
		int fheight=frame.getHeight();
		width=700;
		int height=300;
		int x=(fwidth-width)/2;
		int y=(fheight-height)/2;
		setBounds(x, y, width, height);
	}
	
	private void initForm(JPanel root){
		JPanel form=FormFactory.create(Color.WHITE, null, 2, 4, null);
		FormFactory.addRow(form, 0, "JDBC驱动类：", jdbcDriver=FormFactory.createFormInput(
			Attribute.create()
			.put(Attribute.ATTRIBUTE_FORM_VALUE, QuickApplication.getConfig(QuickConstant.CONF_DATABASE_JDBC_DRIVER))
			.put(Attribute.ATTRIBUTE_FORM_MARGIN,  FormFactory.defaultMargin())
		), null, null);
		jdbcUrl=FormFactory.createFormArea2(
				Attribute.create()
			.put(Attribute.ATTRIBUTE_FORM_VALUE, QuickApplication.getConfig(QuickConstant.CONF_DATABASE_JDBC_URL))
			.put(Attribute.ATTRIBUTE_FORM_EDITABLE, true)
			.put(Attribute.ATTRIBUTE_FORM_MARGIN,  FormFactory.defaultMargin())
			.put(Attribute.ATTRIBUTE_FORM_BORDER, BorderFactory.createLineBorder(new Color(171,173,179)))
		);
		FormFactory.addRow(form, 1, "JDBC URL：", ScrollFactory.addVScroll(jdbcUrl), 75, 500);
		FormFactory.addRow(form, 2, "用户名：", jdbcUsername=FormFactory.createFormInput(
			Attribute.create()
			.put(Attribute.ATTRIBUTE_FORM_VALUE, QuickApplication.getConfig(QuickConstant.CONF_DATABASE_JDBC_USERNAME))
			.put(Attribute.ATTRIBUTE_FORM_MARGIN,  FormFactory.defaultMargin())
		), null, null);
		FormFactory.addRow(form, 3, "密码：", jdbcPassword=FormFactory.createFormInput(
			Attribute.create()
			.put(Attribute.ATTRIBUTE_FORM_VALUE, QuickApplication.getConfig(QuickConstant.CONF_DATABASE_JDBC_PASSWORD))
			.put(Attribute.ATTRIBUTE_FORM_MARGIN,  FormFactory.defaultMargin())
		), null, null);
		root.add(ScrollFactory.addScroll(form, null, null));
	}
	
	public void initBottom(JPanel root){
		JPanel panel=PanelFactory.create(null, null, new FlowLayout(FlowLayout.RIGHT));
		panel.add(ButtonFactory.createDialogButton(
			Attribute.create()
			.put(Attribute.ATTRIBUTE_BUTTON_NAME, "确定")
			.put(Attribute.ATTRIBUTE_BUTTON_ACTION, ButtonConstant.ACTION_DIALOG_CONFIRM)
			.put(Attribute.ATTRIBUTE_BUTTON_DEPEND, this)
		));
		panel.add(ButtonFactory.createDialogButton(
			Attribute.create()
			.put(Attribute.ATTRIBUTE_BUTTON_NAME, "关闭")
			.put(Attribute.ATTRIBUTE_BUTTON_ACTION, ButtonConstant.ACTION_DIALOG_CLOSE)
			.put(Attribute.ATTRIBUTE_BUTTON_DEPEND, this)
		));
		root.add(panel, BorderLayout.SOUTH);
	}
	
	@Override
	public void confirm() {
		if(!validateForm()){
			return ;
		}
		String driver=jdbcDriver.getText().replaceAll("\\s", "");
		String url=jdbcUrl.getText().replaceAll("\\s", "");
		String username=jdbcUsername.getText().replaceAll("\\s", "");
		String password=jdbcPassword.getText().replaceAll("\\s", "");
		DbSession.setInstance(driver, url, username, password);
		List<String> databaseList=new ArrayList<String>();
		DbSession.find("show databases", new FindDataBack() {
			private String[] exclude = QuickApplication.getConfig(QuickConstant.CONF_DATABASE_EXCLUDE).split("\\,");
			public boolean handleRow(Map<String, Object> rowData, int row){
				String databaseName=(String)rowData.get("Database");
				if(ObjectUtils.contains(exclude, databaseName)){
					return true;
				}
				databaseList.add(databaseName);
				return true;
			};
		});
		QuickApplication.setConfig(QuickConstant.CONF_DATABASE_JDBC_DRIVER, driver);
		QuickApplication.setConfig(QuickConstant.CONF_DATABASE_JDBC_URL, url);
		QuickApplication.setConfig(QuickConstant.CONF_DATABASE_JDBC_USERNAME, username);
		QuickApplication.setConfig(QuickConstant.CONF_DATABASE_JDBC_PASSWORD, password);
		
		
		JComboBox<String> databaseSelect=QuickConstant.CACHE_MODULE_DATABASE.equals(action)?QuickApplication.cache.get(QuickConstant.CACHE_MODULE_DATABASE):QuickApplication.cache.getHash("addField", "database");
		databaseSelect.removeAll();
		for (String database : databaseList) {
			databaseSelect.addItem(database);
		}
		String database=(String)databaseSelect.getSelectedItem();
		if(QuickConstant.CACHE_MODULE_DATABASE.equals(action)) {
			Table table = QuickApplication.cache.get(QuickConstant.CACHE_MODULE_TABLE);
			TableFactory.deleteAll(table);
			String floors=QuickApplication.getConfig(QuickConstant.CONF_GENERICS_MODULE_FLOORS);
			String operator=QuickApplication.getConfig(QuickConstant.CONF_GENERICS_MODULE_OPERATORS);
			DbSession.find("select table_name name,table_comment `comment` from information_schema.tables t where table_schema=? and LOWER(table_type)='base table' order by create_time desc", new FindDataBack() {
				@Override
				public boolean handleRow(Map<String, Object> rowData, int row) {
					String tableName = (String)rowData.get("name");
					int index=tableName.indexOf("_");
					String module=QuickApplication.getConfig(QuickConstant.CONF_POJO_TABLE_GENERICS_CONFIG+database+"."+tableName+".module");
					String currModule=QuickApplication.getConfig(QuickConstant.CONF_POJO_TABLE_GENERICS_CONFIG+database+"."+tableName+".currModule");
					String businessModule=QuickApplication.getConfig(QuickConstant.CONF_POJO_TABLE_GENERICS_CONFIG+database+"."+tableName+".businessModule");
					String genericsModule=ObjectUtils.init(QuickApplication.getConfig(QuickConstant.CONF_POJO_TABLE_GENERICS_CONFIG+database+"."+tableName+".genericsModule"), floors);
					String dataOperator=ObjectUtils.init(QuickApplication.getConfig(QuickConstant.CONF_POJO_TABLE_GENERICS_CONFIG+database+"."+tableName+".dataOperator"), operator);
					String server=ObjectUtils.init(QuickApplication.getConfig(QuickConstant.CONF_POJO_TABLE_GENERICS_CONFIG+database+"."+tableName+".server"), "");
					if(index!=-1 && ObjectUtils.isEmpty(currModule)){
						module=tableName.substring(0, index);
						if(tableName.charAt(tableName.length()-1)=='_'){
							tableName=tableName.substring(0, tableName.length()-1);
						}
						currModule=tableName.substring(index+1).replace("_", ".");
					}
					TableFactory.addRowData(table, new Object[]{"", rowData.get("name"), ObjectUtils.init(rowData.get("comment"), ""), server, module, businessModule, currModule, genericsModule, dataOperator});
					return super.handleRow(rowData, row);
				}
			}, database);
		}else if(QuickConstant.CACHE_ADD_FIELD_DATABASE.equals(action)){
			JComboBox<String> tableSelect=QuickApplication.cache.getHash("addField", "table");
			tableSelect.removeAll();
			DbSession.find("select table_name name,table_comment `comment` from information_schema.tables t where table_schema=? and LOWER(table_type)='base table' order by create_time desc", new FindDataBack() {
				@Override
				public boolean handleRow(Map<String, Object> rowData, int row) {
					String tableName = (String)rowData.get("name");
					tableSelect.addItem(tableName+"("+ObjectUtils.init(rowData.get("comment"), "")+")");
					return super.handleRow(rowData, row);
				}
			}, database);
			String tableName=(String)tableSelect.getSelectedItem();
			String moduleText=null;
			String currModuleText=null;
			if(ObjectUtils.isNotEmpty(tableName)) {
				tableName=tableName.substring(0, tableName.indexOf("("));
				currModuleText=QuickApplication.getConfig(QuickConstant.CONF_POJO_TABLE_GENERICS_CONFIG+database+"."+tableName+".currModule");
				moduleText=QuickApplication.getConfig(QuickConstant.CONF_POJO_TABLE_GENERICS_CONFIG+database+"."+tableName+".module");
				int index=tableName.indexOf("_");
				if(index!=-1 && ObjectUtils.isEmpty(currModuleText)){
					moduleText=tableName.substring(0, index);
					if(tableName.charAt(tableName.length()-1)=='_'){
						tableName=tableName.substring(0, tableName.length()-1);
					}
					currModuleText=tableName.substring(index+1).replace("_", ".");
				}
			}
			JTextField module=QuickApplication.cache.getHash("addField", "module");
			module.setText(moduleText);
			JTextField currModule=QuickApplication.cache.getHash("addField", "currModule");
			currModule.setText(currModuleText);
			JTextField fieldName=QuickApplication.cache.getHash("addField", "fieldName");
			fieldName.setText("");
			JTextField fieldLength=QuickApplication.cache.getHash("addField", "fieldLength");
			fieldLength.setText("");
			JTextField fieldScale=QuickApplication.cache.getHash("addField", "fieldScale");
			fieldScale.setText("");
			JTextField fieldDefault=QuickApplication.cache.getHash("addField", "fieldDefault");
			fieldDefault.setText("");
		}else {
			JComboBox<String> tableSelect=QuickApplication.cache.getHash("dropField", "table");
			tableSelect.removeAll();
			DbSession.find("select table_name name,table_comment `comment` from information_schema.tables t where table_schema=? and LOWER(table_type)='base table' order by create_time desc", new FindDataBack() {
				@Override
				public boolean handleRow(Map<String, Object> rowData, int row) {
					String tableName = (String)rowData.get("name");
					tableSelect.addItem(tableName+"("+ObjectUtils.init(rowData.get("comment"), "")+")");
					return super.handleRow(rowData, row);
				}
			}, database);
			String tableName=(String)tableSelect.getSelectedItem();
			String moduleText=null;
			String currModuleText=null;
			if(ObjectUtils.isNotEmpty(tableName)) {
				tableName=tableName.substring(0, tableName.indexOf("("));
				currModuleText=QuickApplication.getConfig(QuickConstant.CONF_POJO_TABLE_GENERICS_CONFIG+database+"."+tableName+".currModule");
				moduleText=QuickApplication.getConfig(QuickConstant.CONF_POJO_TABLE_GENERICS_CONFIG+database+"."+tableName+".module");
				int index=tableName.indexOf("_");
				if(index!=-1 && ObjectUtils.isEmpty(currModuleText)){
					moduleText=tableName.substring(0, index);
					if(tableName.charAt(tableName.length()-1)=='_'){
						tableName=tableName.substring(0, tableName.length()-1);
					}
					currModuleText=tableName.substring(index+1).replace("_", ".");
				}
			}
			JTextField module=QuickApplication.cache.getHash("dropField", "module");
			module.setText(moduleText);
			JTextField currModule=QuickApplication.cache.getHash("dropField", "currModule");
			currModule.setText(currModuleText);
			JTextField fieldName=QuickApplication.cache.getHash("dropField", "fieldName");
			fieldName.setText("");
		}
		this.close();
	}
	
	public boolean validateForm(){
		if(ObjectUtils.isEmpty(jdbcDriver.getText())){
			MessageFactory.error(this, "JDBC驱动类不能为空");
			return false;
		}
		if(ObjectUtils.isEmpty(jdbcUrl.getText())){
			MessageFactory.error(this, "JDBC URL不能为空");
			return false;
		}
		if(ObjectUtils.isEmpty(jdbcUsername.getText())){
			MessageFactory.error(this, "用户名不能为空");
			return false;
		}
		if(ObjectUtils.isEmpty(jdbcPassword.getText())){
			MessageFactory.error(this, "密码不能为空");
			return false;
		}
		return true;
	}
}
